<?php

namespace backend\modules\sys\controllers;


use common\models\common\AuthRole;
use Yii;
use common\enums\StatusEnum;
use common\models\common\SearchModel;
use common\components\Curd;
use common\models\sys\Manager;
use common\helpers\ArrayHelper;
use common\helpers\ResultDataHelper;
use backend\controllers\BaseController;
use backend\modules\sys\forms\PasswdForm;
use backend\modules\sys\forms\ManagerForm;
use common\models\common\AuthAssignment;

/**
 * Class ManagerController
 * @package backend\modules\sys\controllers
 * @author  jianyan74 <751393839@qq.com>
 */
class OperateController extends BaseController
{
    use Curd;

    /**
     * @var Manager
     */
    public $modelClass = Manager::class;
    
    /**
     *运营中心页面
     */
    public function actionOperate()
    {
        // 获取当前运营中心的下面的所有用户id，除超级管理员
        $isLevel = AuthAssignment::find()
                                 ->select('user_id')
                                 ->where(['role_id' => '3'])
                                 ->asArray()
                                 ->all();
        foreach ($isLevel as $key) {
            $level[] = $key['user_id'];
        }
        $searchModel  = new SearchModel([
            'model'                  => $this->modelClass,
            'scenario'               => 'default',
            'partialMatchAttributes' => ['username', 'mobile', 'realname'], // 模糊查询
            'defaultOrder'           => [
                'type' => SORT_DESC,
                'id'   => SORT_DESC,
            ],
            'pageSize'               => $this->pageSize,
        ]);
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                            ->andFilterWhere(['in', 'id', $level])
                            ->andWhere(['>=', 'status', StatusEnum::DISABLED])
                            ->with('assignment');

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel'  => $searchModel,
        ]);
    }
    
    /**
     * 编辑/创建
     * @return mixed|string|\yii\web\Response
     * @throws \yii\base\ExitException
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     */
    public function actionAjaxEdit()
    {
        $request   = Yii::$app->request;
        $model     = new ManagerForm();
        $model->id = $request->get('id');
        //根据level来判断 新角色的权限构成
        $level = $request->get('level');
        $model->loadData();
        $model->id != Yii::$app->params['adminAccount'] && $model->scenario = 'generalAdmin';
        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load($request->post())) {
            // 记录行为日志
            Yii::$app->services->sysActionLog->create('managerEdit',
                '创建/编辑管理员密码|账号:' . $model->username, FALSE);

            return $model->save()
                ? $this->redirect(['operate'])
                : $this->message($this->getError($model), $this->redirect(['operate']), 'error');
        }
        // 获取权限信息
        $role  = AuthRole::find()
                         ->where(['level' => $level])
                         ->asArray()
                         ->one();
        $roles = [$role['id'] => $role['title']];
        //获取父级
        $prole = $role['level'] - 1;
        if ($prole != 0) {
            $assignment = AuthAssignment::find()
                                        ->select('user_id,')
                                        ->where(['=', 'role_id', $prole])
                                        ->asArray()
                                        ->all();
            foreach ($assignment as $item) {
                $map[] = $item['user_id'];
            }
            $upManager = Manager::find()
                                ->select('username,id')
                                ->where(['in', 'id', $map])
                                ->asArray()
                                ->all();
            $p_role    = ArrayHelper::map($upManager, 'id', 'username');
        }else {
            $p_role = ['1' => '最高级'];
        }

        return $this->renderAjax($this->action->id, [
            'model'  => $model,
            'roles'  => $roles,
            'p_role' => $p_role,
        ]);
    }
    /**
     * 编辑/创建
     *
     * @return mixed
     */
    public function actionEdit()
    {
//        echo $this->getMerchantId();die;
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['operate']);
        }
        $model->merchant_id =$this->getMerchantId();
        return $this->render($this->action->id, [
            'model' => $model,
        ]);
    }

    /**
     * 个人中心
     * @return mixed|string
     */
    public function actionPersonal()
    {
        $id    = Yii::$app->user->id;
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->message('修改个人信息成功', $this->redirect(['personal']));
        }

        return $this->render($this->action->id, [
            'model' => $model,
        ]);
    }
    /**
     * 伪删除
     *
     * @param $id
     * @return mixed
     */
    public function actionDestroy($id)
    {
        if (!($model = $this->modelClass::findOne($id))) {
            return $this->message("找不到数据", $this->redirect(['operate']), 'error');
        }

        $model->status = StatusEnum::DELETE;
        if ($model->save()) {
            return $this->message("删除成功", $this->redirect(['operate']));
        }

        return $this->message("删除失败", $this->redirect(['operate']), 'error');
    }

    /**
     * 修改密码
     * @return array|string
     * @throws \yii\base\Exception
     * @throws \yii\base\InvalidConfigException
     */
    public function actionUpPassword()
    {
        $model = new PasswdForm();
        if ($model->load(Yii::$app->request->post())) {
            if (!$model->validate()) {
                return ResultDataHelper::json(404, $this->getError($model));
            }
            /* @var $manager \common\models\sys\Manager */
            $manager                = Yii::$app->user->identity;
            $manager->password_hash = Yii::$app->security->generatePasswordHash($model->passwd_new);;
            // 记录行为日志
            Yii::$app->services->sysActionLog->create('updateManagerPwd',
                '修改管理员密码|账号:' . $manager->username, FALSE);
            if ($manager->save()) {
                Yii::$app->user->logout();

                return ResultDataHelper::json(200, '修改成功');
            }

            return ResultDataHelper::json(404, $this->analyErr($manager->getFirstErrors()));
        }

        return $this->render($this->action->id, [
            'model' => $model,
        ]);
    }

    /**
     * @param \yii\base\Action $action
     * @param mixed            $result
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function afterAction($action, $result)
    {
        if ($action->id == 'delete') {
            Yii::$app->services->sysActionLog->create('managerDel', '删除管理员');
        }

        return parent::afterAction($action, $result);
    }

}